package javabase.ionio.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 *  如果仅仅只是让某个类实现Serializable接口，而没有其它任何处理的话，则就是使用默认序列化机制
 */
class Person implements Serializable {
	
	private static final long serialVersionUID = 1L;
	private String name;
	// 当某个字段被声明为transient后，默认序列化机制就会忽略该字段
	private transient int age;
	
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

	/*
	 * 重新让age恢复序列化方法：
	 * 1.去掉transient关键字
	 * 2.在Person类中添加两个方法：writeObject()与readObject()
	 */
    private void writeObject(ObjectOutputStream out) throws IOException {
        out.defaultWriteObject();
        out.writeInt(age);
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        age = in.readInt();
    }
	
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
	
}

public class SerializableDemo0 {

	public static void main(String[] args) {
		File file = new File("person.out");

        ObjectOutputStream oout = null;
		try {
			oout = new ObjectOutputStream(new FileOutputStream(file));
			Person person = new Person("John", 101);
			oout.writeObject(person);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (oout != null) {
				try {
					oout.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
  
        ObjectInputStream oin = null;
		try {
			oin = new ObjectInputStream(new FileInputStream(file));
			Object newPerson = oin.readObject(); // 没有强制转换到Person类型
			System.out.println(newPerson);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}  catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				oin.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
